import {PluginCommand} from "../PluginCommand";
import {Point} from "../../../nodeApp/static/lib/crowncad-plugin-sdk-0.0.1";

class WingTwistDesignCommand extends PluginCommand {
  constructor() {
    super();
  }
  //绘制翼型设计草图
  async createWingTwistBySection(params) {
    //创建通过XYZ点的三维曲线
    let guideLineIds = [];
    for(let i = 0; i < params?.guideLinesInfo?.length; i++) {
      let pointsInfo = params.guideLinesInfo[i];
      let points = [];
      pointsInfo?.forEach(point => {
        points.push(new Point(point.x, point.y, point.z));
      })
      let curveRes = await this.command.curve.createCurveByXYZPointsIncrement({
        points: points,
      })
      let currentFeature = curveRes?.data?.modelData?.currentFeature;
      if (currentFeature && currentFeature.length > 0) {
        let entities = await this.query.getEntitiesByFeatureIds([currentFeature[0]?.id]);
        let entitiesData = entities?.data?.entities;
        if (entitiesData && entitiesData.length > 0) {
          guideLineIds.push(entitiesData[0].id);
        }
      }
    }

    //根据样条曲线上的点创建多个轮廓草图
    let sketchEntityIds = [];
    for (let i = 0; i < params.sketchesInfo?.length; i++) {
      let pointsInfo = params.sketchesInfo[i];
      this.command.sketch.create3DSketch({sketchName: ''});
      let lineInfo = [];
      pointsInfo?.forEach(point => {
        lineInfo.push(new Point(point.x, point.y, point.z));
      })
      let sketchInfoUp = lineInfo.toReversed().slice(lineInfo.length / 2);
      let sketchInfoDown = lineInfo.slice(lineInfo.length / 2);
      this.command.sketch.createIntpCurve({
        pickPoints: sketchInfoUp,
      })
      this.command.sketch.createIntpCurve({
        pickPoints: sketchInfoDown,
      })
      this.command.sketch.exitSketch();
      let res = await this.command.executeIncrementCommand(this.command.commandScript);
      this.command.clearCommand();
      let currentFeature = res?.data?.modelData?.currentFeature;
      if (currentFeature && currentFeature.length > 0) {
        let entities = await this.query.getEntitiesByFeatureIds([currentFeature[0]?.id]);
        let entitiesData = entities?.data?.entities;
        if (entitiesData && entitiesData.length > 0) {
          sketchEntityIds.push(entitiesData[0].id);
        }
      }
    }
    //放样曲面
    await this.command.surface.loftSurfaceIncrement({
      profiles: sketchEntityIds,
      hasGuideCurve: guideLineIds.length > 0 ? 1 : 0,
      guideCurves: guideLineIds,
    })
  }

  getElementsByEntityId(entityId, cb) {
    let elements = [];
    this.query.getElementsByEntityId(entityId).then(elementsOnEntity => {
      let resData = elementsOnEntity?.data?.elements;
      if (elementsOnEntity?.code === 200 && resData?.length > 0) {
        for (let i = 0; i < resData.length; i++) {
          elements.push(resData[i]);
        }
      }
      cb(elements);
    });
  }
}

const wingTwistDesignCommand = new WingTwistDesignCommand();
export {wingTwistDesignCommand};
